'''
Created on 11 juin 2013

@author: Nils Amiet
'''

from subprocess import Popen, PIPE
import os

class SentiStrength():
    '''Wrapper class for SentiStrength java version'''
    
    RUN_COMMAND = "java -jar"
    SENTISTRENGTH_PATH = os.path.join(os.path.dirname(__file__), "SentiStrengthCom.jar")
    DATA_PATH = os.path.join(os.path.dirname(__file__), "SentStrength_Data_Sept2011/")
    
    def __init__(self):
        pass
    
    def classifiy(self, text):
        commandArgs = "%s %s sentidata %s cmd" % (self.RUN_COMMAND, self.SENTISTRENGTH_PATH, self.DATA_PATH)
        commandArgs = commandArgs.split(" ")
        
        process = Popen(commandArgs, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        text = text.replace(" ", "+")
        classification, dummy = process.communicate(text.encode("utf-8"))
        
        polarities = classification.split("\n")
        polarities = [self.polarity(line.strip()) for line in polarities]
        polarities = [x for x in polarities if x is not None]
        
        return polarities
    
    def polarity(self, line):
        val = line.split(" ")
        try:
            val = [int(x) for x in val]
        except:
            return None
        
        return sum(val)